<template>
  <div class="dashboard-container">
    <a-row :gutter="16">
      <a-col :span="8">
        <a-card>
          <template #title>
            <span><user-outlined /> 用户统计</span>
          </template>
          <div class="statistic-card">
            <a-statistic title="总用户数" :value="dashboardData.userCount" />
            <a-divider />
            <div class="sub-statistics">
              <a-statistic title="今日新增" :value="dashboardData.todayNewUsers" />
              <a-statistic title="本周新增" :value="dashboardData.weekNewUsers" />
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <template #title>
            <span><database-outlined /> 血糖记录统计</span>
          </template>
          <div class="statistic-card">
            <a-statistic title="总记录数" :value="dashboardData.recordCount" />
            <a-divider />
            <div class="sub-statistics">
              <a-statistic title="今日新增" :value="dashboardData.todayNewRecords" />
              <a-statistic title="本周新增" :value="dashboardData.weekNewRecords" />
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <template #title>
            <span><pie-chart-outlined /> 血糖状态分布</span>
          </template>
          <div class="statistic-card">
            <div class="status-statistics">
              <a-statistic 
                title="正常" 
                :value="dashboardData.normalRecords" 
                :value-style="{ color: '#52c41a' }" 
              />
              <a-statistic 
                title="偏低" 
                :value="dashboardData.lowRecords" 
                :value-style="{ color: '#faad14' }" 
              />
              <a-statistic 
                title="偏高" 
                :value="dashboardData.highRecords" 
                :value-style="{ color: '#f5222d' }" 
              />
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-card title="近7日血糖记录趋势" class="chart-card">
      <div ref="trendChartRef" style="width: 100%; height: 400px"></div>
    </a-card>

    <a-row :gutter="16">
      <a-col :span="12">
        <a-card title="用户类型分布" class="chart-card">
          <div ref="userTypeChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="最近操作日志" class="chart-card">
          <a-list
            :data-source="logs"
            :pagination="{ pageSize: 5 }"
            item-layout="horizontal"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    <span>{{ item.title }}</span>
                  </template>
                  <template #description>
                    <span>{{ item.content }}</span>
                  </template>
                  <template #avatar>
                    <a-avatar :icon="getLogIcon(item.type)" />
                  </template>
                </a-list-item-meta>
                <div>{{ formatTime(item.time) }}</div>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, h } from 'vue';
import { UserOutlined, DatabaseOutlined, PieChartOutlined, EditOutlined, DeleteOutlined, LoginOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import { LineChart, PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  LineChart,
  PieChart,
  CanvasRenderer
]);

// 仪表盘数据
const dashboardData = ref({
  userCount: 0,
  todayNewUsers: 0,
  weekNewUsers: 0,
  recordCount: 0,
  todayNewRecords: 0,
  weekNewRecords: 0,
  normalRecords: 0,
  lowRecords: 0,
  highRecords: 0
});

// 趋势图数据
const trendData = ref([]);

// 用户类型分布
const userTypes = ref([]);

// 操作日志
const logs = ref([]);

// 图表引用
const trendChartRef = ref(null);
const userTypeChartRef = ref(null);

// 图表实例
let trendChart = null;
let userTypeChart = null;

// 模拟获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    // 实际开发中这里应该调用后端接口获取数据
    // 这里暂时使用模拟数据
    dashboardData.value = {
      userCount: 256,
      todayNewUsers: 12,
      weekNewUsers: 45,
      recordCount: 1856,
      todayNewRecords: 78,
      weekNewRecords: 356,
      normalRecords: 1234,
      lowRecords: 321,
      highRecords: 301
    };

    // 模拟近7天的血糖记录趋势
    const now = new Date();
    trendData.value = Array.from({ length: 7 }, (_, i) => {
      const date = new Date(now);
      date.setDate(date.getDate() - (6 - i));
      return {
        date: `${date.getMonth() + 1}-${date.getDate()}`,
        count: Math.floor(Math.random() * 50) + 20,
        avgValue: (Math.random() * 2 + 4.5).toFixed(1)
      };
    });

    // 模拟用户类型分布
    userTypes.value = [
      { name: '1型糖尿病', value: 56 },
      { name: '2型糖尿病', value: 138 },
      { name: '妊娠糖尿病', value: 42 },
      { name: '其他类型', value: 20 }
    ];

    // 模拟操作日志
    logs.value = [
      { title: '用户登录', content: '管理员admin登录系统', type: 'login', time: new Date() },
      { title: '编辑用户', content: '编辑用户ID:123的信息', type: 'edit', time: new Date(Date.now() - 3600000) },
      { title: '删除记录', content: '删除血糖记录ID:456', type: 'delete', time: new Date(Date.now() - 7200000) },
      { title: '添加用户', content: '新增管理员用户:test', type: 'add', time: new Date(Date.now() - 86400000) },
      { title: '导出数据', content: '导出用户数据报表', type: 'export', time: new Date(Date.now() - 172800000) },
      { title: '系统设置', content: '修改系统配置', type: 'setting', time: new Date(Date.now() - 259200000) }
    ];

    // 渲染图表
    renderTrendChart();
    renderUserTypeChart();
  } catch (error) {
    console.error('获取仪表盘数据错误', error);
  }
};

// 渲染血糖趋势图
const renderTrendChart = () => {
  if (!trendChartRef.value) return;
  
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value);
  }
  
  const dates = trendData.value.map(item => item.date);
  const counts = trendData.value.map(item => item.count);
  const avgValues = trendData.value.map(item => item.avgValue);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['记录数', '平均血糖']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: dates
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '记录数',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '血糖值 (mmol/L)',
        axisLabel: {
          formatter: '{value}'
        },
        min: 3,
        max: 8
      }
    ],
    series: [
      {
        name: '记录数',
        type: 'bar',
        data: counts,
        itemStyle: {
          color: '#91d5ff'
        }
      },
      {
        name: '平均血糖',
        type: 'line',
        yAxisIndex: 1,
        data: avgValues,
        itemStyle: {
          color: '#f5222d'
        },
        smooth: true
      }
    ]
  };
  
  trendChart.setOption(option);
};

// 渲染用户类型分布图
const renderUserTypeChart = () => {
  if (!userTypeChartRef.value) return;
  
  if (!userTypeChart) {
    userTypeChart = echarts.init(userTypeChartRef.value);
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: userTypes.value.map(item => item.name)
    },
    series: [
      {
        name: '用户类型',
        type: 'pie',
        radius: '60%',
        center: ['50%', '50%'],
        data: userTypes.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          formatter: '{b}: {c} ({d}%)'
        }
      }
    ]
  };
  
  userTypeChart.setOption(option);
};

// 获取日志图标
const getLogIcon = (type) => {
  switch (type) {
    case 'edit': return () => h(EditOutlined);
    case 'delete': return () => h(DeleteOutlined);
    case 'login': return () => h(LoginOutlined);
    default: return () => h(EditOutlined);
  }
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 窗口大小调整时重新渲染图表
const handleResize = () => {
  trendChart?.resize();
  userTypeChart?.resize();
};

// 组件挂载
onMounted(() => {
  fetchDashboardData();
  window.addEventListener('resize', handleResize);
});

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  trendChart?.dispose();
  userTypeChart?.dispose();
});
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
}

.statistic-card {
  padding: 8px 0;
}

.sub-statistics {
  display: flex;
  justify-content: space-between;
}

.status-statistics {
  display: flex;
  justify-content: space-between;
}

.chart-card {
  margin-top: 24px;
}
</style> 